module(...,package.seeall)

local physics = require "physics"
local background
local gamePlayGroup
local jarOfGems
local ballons
local gems
local levelNumber
local countBallon
local sceneGroup
local generatorTimerId
local callLevelEndPopup
local removedBallons
local popedBallons
local BALLON_POINTS = 20
local GEM_POINTS = 40
local totalScore
local countGem
local levelManager = require("Level")
local levelDefinition
local jewelAudio = audio.loadSound("jewelcollision.wav")
local levelScoreValue

local function createLevel()
	
	ballons = {}
	gems = {}	
	countBallon = 1
	countGem = 1
	physics.start()
	
	levelDefinition = levelManager.getLevelDefinition(global_levelNumber)
	
	print("Level bg " .. levelDefinition.bg)
	
	gameBg = display.newImageRect(levelDefinition.bg,BASE_SCREEN_WIDTH,BASE_SCREEN_HEIGHT)
	gameBg.x = display.contentWidth / 2
	gameBg.y = display.contentHeight / 2     
	
	--physics.setDrawMode("hybrid")

	print(levelDefinition.jewelJar.jar)
	
	jarOfGems = display.newImageRect(levelDefinition.jewelJar.jar..".png",levelDefinition.jewelJar.width,levelDefinition.jewelJar.height)
	
	jarOfGems.x = levelDefinition.jewelJar.xPosition
	jarOfGems.y = levelDefinition.jewelJar.yPosition
	gamePlayGroup:insert(3,jarOfGems)
	local jarData = (require(levelDefinition.jewelJar.jar)).physicsData(1)
	physics.addBody(jarOfGems,"static",jarData:get(levelDefinition.jewelJar.jar))
	
	gamePlayGroup:insert(1,gameBg)
	
end

function calculateScore()
	local totalGems = 0	
	for count=1,#gems do
		if (gems[count].lost == false) then
			totalGems = totalGems + 1
		end
	end	
	totalScore = (popedBallons * BALLON_POINTS) + (totalGems * GEM_POINTS)
	
	-- Ajusta os zeros a esquerda para manter o tamanho da string
	
	return totalScore
end

function createLevelBallons(level,displayGroup,callLevelEnd,levelscore)

	callLevelEndPopup = callLevelEnd
	gamePlayGroup = display.newGroup()
	displayGroup:insert(gamePlayGroup)
	levelScoreValue = levelscore
	
	
	levelNumber = level
	print("Level number " .. levelNumber)
	createLevel()	
	
	removedBallons = 0
	popedBallons = 0
	ballon = require("Ballon")
	
	local function touchBallon(event)
		if (event.phase == "began") then
			print(event.target.YSpeed)
			event.target:removeEventListener("touch",touchBallon)
			local gem = event.target.popBallon()
			gem.lost = false
			gamePlayGroup:insert(2,gem)
			-- Select the correct gem physics file
		
			print(gem.kind.name)
		
			local gemData = (require "jewels").physicsData(1)
			physics.addBody(gem,gemData:get(gem.kind.name))
		
			-- local collision listener / function listener
			local function oncollision(event)	
				if (event.phase == "began") then
					print("Jewel Collided")
					audio.play(jewelAudio)
				else
					event.target:removeEventListener("collision",oncollision)
				end
			end
			gem:addEventListener("collision",oncollision)
			print("Remove ballon by touch "..event.target.idBallon)
			removedBallons = removedBallons + 1
			ballons[event.target.idBallon] = nil
			popedBallons = popedBallons + 1	
			gems[countGem] = gem
			countGem = countGem + 1
		end
	
	end
	
	function handleEnterFrame()
		
		for count=1,#gems do				
			if ((gems[count].y > display.contentHeight) and (gems[count].lost == false)) then
				print(" Gem Lost !")
				gems[count].lost = true
			end			
		end
		
		if (removedBallons == levelNumber) then
			print("remove enterFrame listener and call end level popup")
			Runtime:removeEventListener("enterFrame",handleEnterFrame)

			-- Calcular o score
			
			local function loadEndLevel(event)
				local score = calculateScore()
				--print(" Score from game controller " .. score)
				callLevelEndPopup(score)
			end
			
			timer.performWithDelay(1500,loadEndLevel)
			
		else
			for count=1,levelNumber do	
				if (ballons[count] ~= nil) then
					if (ballons[count].y <= -20) then
						print("remove ballon out of screen "..count)
						ballons[count] = nil
						removedBallons = removedBallons + 1
					else
						ballons[count].moveBallon()			
					end
				end	
			end		
		end
	
		
		levelScoreValue.text = calculateScore()
	end
			
	local function generateBallons(event)
		print("Creating ballon "..countBallon)		
		ballons[countBallon] = ballon.createBallon()		
		ballons[countBallon].idBallon = countBallon
		gamePlayGroup:insert(4,ballons[countBallon])			
		physics.addBody(ballons[countBallon],"kinematic",{filter={maskBits=0}})
		ballons[countBallon]:setLinearVelocity(0,ballons[countBallon].YSpeed)
		ballons[countBallon]:addEventListener("touch",touchBallon)
		if (countBallon == 1) then
			print("Start enterFrame listener")
			Runtime:addEventListener("enterFrame",handleEnterFrame)	
		end
		countBallon = countBallon + 1	
	end
	generatorTimerId = timer.performWithDelay(1000,generateBallons,level)
		
end

function pauseGame()
	physics.pause()
	timer.pause(generatorTimerId)
end

function resumeGame()
	physics.start()
	timer.resume(generatorTimerId)
end

function destroyGameController()
	print("Destroy Game controller")
	Runtime:removeEventListener("enterFrame",handleEnterFrame)
	timer.cancel(generatorTimerId)
	ballons = {}
	physics.stop()
end